import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Select, 
  Switch, 
  message, 
  Popconfirm,
  Card,
  Tag,
  Tabs,
  InputNumber
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  BookOutlined,
  QuestionCircleOutlined
} from '@ant-design/icons';
import { api } from '../utils/api';

const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

interface Question {
  id: number;
  title: string;
  content: string;
  type: string;
  difficulty: string;
  options: any;
  correct_answer: string;
  explanation: string;
  score: number;
  is_active: boolean;
  created_at: string;
  category: {
    id: number;
    name: string;
  };
}

interface Category {
  id: number;
  name: string;
  description: string;
  sort_order: number;
  is_active: boolean;
}

const QuestionManagement: React.FC = () => {
  const [questions, setQuestions] = useState<Question[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [categoryModalVisible, setCategoryModalVisible] = useState(false);
  const [editingQuestion, setEditingQuestion] = useState<Question | null>(null);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [questionForm] = Form.useForm();
  const [categoryForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  useEffect(() => {
    fetchQuestions();
    fetchCategories();
  }, [pagination.current, pagination.pageSize]);

  const fetchQuestions = async () => {
    try {
      setLoading(true);
      const response = await api.get('/questions/admin/', {
        params: {
          page: pagination.current,
          per_page: pagination.pageSize
        }
      });

      if (response.data.success) {
        setQuestions(response.data.data.items);
        setPagination(prev => ({
          ...prev,
          total: response.data.data.total
        }));
      }
    } catch (error) {
      message.error('获取题目列表失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchCategories = async () => {
    try {
      const response = await api.get('/questions/admin/categories');
      if (response.data.success) {
        setCategories(response.data.data);
      }
    } catch (error) {
      message.error('获取分类列表失败');
    }
  };

  const handleCreateQuestion = () => {
    setEditingQuestion(null);
    questionForm.resetFields();
    setModalVisible(true);
  };

  const handleEditQuestion = (record: Question) => {
    setEditingQuestion(record);
    questionForm.setFieldsValue({
      title: record.title,
      content: record.content,
      type: record.type,
      difficulty: record.difficulty,
      category_id: record.category.id,
      options: record.options,
      correct_answer: record.correct_answer,
      explanation: record.explanation,
      score: record.score,
      is_active: record.is_active
    });
    setModalVisible(true);
  };

  const handleDeleteQuestion = async (id: number) => {
    try {
      await api.delete(`/questions/admin/${id}`);
      message.success('删除成功');
      fetchQuestions();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleQuestionSubmit = async (values: any) => {
    try {
      if (editingQuestion) {
        await api.put(`/questions/admin/${editingQuestion.id}`, values);
        message.success('更新成功');
      } else {
        await api.post('/questions/admin/', values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchQuestions();
    } catch (error) {
      message.error(editingQuestion ? '更新失败' : '创建失败');
    }
  };

  const handleCreateCategory = () => {
    setEditingCategory(null);
    categoryForm.resetFields();
    setCategoryModalVisible(true);
  };

  const handleEditCategory = (record: Category) => {
    setEditingCategory(record);
    categoryForm.setFieldsValue({
      name: record.name,
      description: record.description,
      sort_order: record.sort_order,
      is_active: record.is_active
    });
    setCategoryModalVisible(true);
  };

  const handleDeleteCategory = async (id: number) => {
    try {
      await api.delete(`/questions/admin/categories/${id}`);
      message.success('删除成功');
      fetchCategories();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleCategorySubmit = async (values: any) => {
    try {
      if (editingCategory) {
        await api.put(`/questions/admin/categories/${editingCategory.id}`, values);
        message.success('更新成功');
      } else {
        await api.post('/questions/admin/categories', values);
        message.success('创建成功');
      }
      setCategoryModalVisible(false);
      fetchCategories();
    } catch (error) {
      message.error(editingCategory ? '更新失败' : '创建失败');
    }
  };

  const questionColumns = [
    {
      title: '题目',
      dataIndex: 'title',
      key: 'title',
      width: 300,
      render: (text: string) => (
        <div style={{ maxWidth: 300, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {text}
        </div>
      )
    },
    {
      title: '分类',
      dataIndex: ['category', 'name'],
      key: 'category',
      width: 100
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => {
        const typeMap: { [key: string]: string } = {
          'single_choice': '单选题',
          'multiple_choice': '多选题',
          'true_false': '判断题',
          'fill_blank': '填空题'
        };
        return <Tag color="blue">{typeMap[type] || type}</Tag>;
      }
    },
    {
      title: '难度',
      dataIndex: 'difficulty',
      key: 'difficulty',
      width: 80,
      render: (difficulty: string) => {
        const colorMap: { [key: string]: string } = {
          'easy': 'green',
          'medium': 'orange',
          'hard': 'red'
        };
        const textMap: { [key: string]: string } = {
          'easy': '简单',
          'medium': '中等',
          'hard': '困难'
        };
        return <Tag color={colorMap[difficulty]}>{textMap[difficulty]}</Tag>;
      }
    },
    {
      title: '分值',
      dataIndex: 'score',
      key: 'score',
      width: 80
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 80,
      render: (active: boolean) => (
        <Tag color={active ? 'green' : 'red'}>
          {active ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: Question) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditQuestion(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这道题目吗？"
            onConfirm={() => handleDeleteQuestion(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  const categoryColumns = [
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
      width: 200
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 300
    },
    {
      title: '排序',
      dataIndex: 'sort_order',
      key: 'sort_order',
      width: 80
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 80,
      render: (active: boolean) => (
        <Tag color={active ? 'green' : 'red'}>
          {active ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: Category) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditCategory(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个分类吗？"
            onConfirm={() => handleDeleteCategory(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <Tabs defaultActiveKey="questions">
        <TabPane tab={<span><QuestionCircleOutlined />题目管理</span>} key="questions">
          <Card title="题目管理" extra={
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateQuestion}>
              新建题目
            </Button>
          }>
            <Table
              columns={questionColumns}
              dataSource={questions}
              rowKey="id"
              loading={loading}
              pagination={{
                ...pagination,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
              }}
              onChange={(pagination) => {
                setPagination(prev => ({
                  ...prev,
                  current: pagination.current || 1,
                  pageSize: pagination.pageSize || 10
                }));
              }}
            />
          </Card>
        </TabPane>

        <TabPane tab={<span><BookOutlined />分类管理</span>} key="categories">
          <Card title="题目分类管理" extra={
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateCategory}>
              新建分类
            </Button>
          }>
            <Table
              columns={categoryColumns}
              dataSource={categories}
              rowKey="id"
              pagination={false}
            />
          </Card>
        </TabPane>
      </Tabs>

      {/* 题目编辑模态框 */}
      <Modal
        title={editingQuestion ? '编辑题目' : '新建题目'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          form={questionForm}
          layout="vertical"
          onFinish={handleQuestionSubmit}
        >
          <Form.Item
            name="title"
            label="题目"
            rules={[{ required: true, message: '请输入题目' }]}
          >
            <TextArea rows={3} placeholder="请输入题目" />
          </Form.Item>

          <Form.Item
            name="category_id"
            label="分类"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select placeholder="请选择分类">
              {categories.map(category => (
                <Option key={category.id} value={category.id}>
                  {category.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="type"
            label="题目类型"
            rules={[{ required: true, message: '请选择题目类型' }]}
          >
            <Select placeholder="请选择题目类型">
              <Option value="single_choice">单选题</Option>
              <Option value="multiple_choice">多选题</Option>
              <Option value="true_false">判断题</Option>
              <Option value="fill_blank">填空题</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="difficulty"
            label="难度"
            rules={[{ required: true, message: '请选择难度' }]}
          >
            <Select placeholder="请选择难度">
              <Option value="easy">简单</Option>
              <Option value="medium">中等</Option>
              <Option value="hard">困难</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="score"
            label="分值"
            rules={[{ required: true, message: '请输入分值' }]}
          >
            <InputNumber min={1} max={100} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="content"
            label="题目内容"
          >
            <TextArea rows={4} placeholder="请输入题目内容（可选）" />
          </Form.Item>

          <Form.Item
            name="options"
            label="选项"
          >
            <TextArea rows={4} placeholder="请输入选项，JSON格式" />
          </Form.Item>

          <Form.Item
            name="correct_answer"
            label="正确答案"
            rules={[{ required: true, message: '请输入正确答案' }]}
          >
            <Input placeholder="请输入正确答案" />
          </Form.Item>

          <Form.Item
            name="explanation"
            label="解析"
          >
            <TextArea rows={3} placeholder="请输入解析" />
          </Form.Item>

          <Form.Item
            name="is_active"
            label="启用状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingQuestion ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 分类编辑模态框 */}
      <Modal
        title={editingCategory ? '编辑分类' : '新建分类'}
        open={categoryModalVisible}
        onCancel={() => setCategoryModalVisible(false)}
        footer={null}
        width={500}
      >
        <Form
          form={categoryForm}
          layout="vertical"
          onFinish={handleCategorySubmit}
        >
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="分类描述"
          >
            <TextArea rows={3} placeholder="请输入分类描述" />
          </Form.Item>

          <Form.Item
            name="sort_order"
            label="排序"
          >
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="is_active"
            label="启用状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingCategory ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setCategoryModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default QuestionManagement; 